/**
 * Copyright(c) 2013 Jade Techonologies Co., Ltd.
 *
 * History:
 *   13-4-23 下午10:08 Created by dwzhang
 */
package com.jade.framework.base.criterion.sql;

import com.jade.framework.base.criterion.Constants;
import com.jade.framework.base.criterion.CriterionInterpreter;

/**
 * Distinct解释器.
 *
 * @author dwzhang
 * @version 1.0 13-4-23 下午10:08
 */
public class DistinctInterpreter implements CriterionInterpreter<SqlContext, Boolean>
{
    public void interprete(SqlContext context, Boolean distinct)
    {
        String sql = context.getContextString();
        boolean flag = sql.toUpperCase().trim().startsWith(Constants.SELECT);
        if (flag) {
            //有select的处理
            int index = sql.toUpperCase().indexOf(Constants.SELECT);
            String suffix = sql.substring(index + Constants.SELECT.length());
            context.getNativeString().delete(index + Constants.SELECT.length(), sql.length());
            injectSQL(context);
            context.append(suffix);
        }
    }

    /**
     * 注入distinct sql语句.
     *
     * @param context 解释器上下文
     */
    private void injectSQL(SqlContext context)
    {
        context.append(Constants.BLANK);
        context.append(Constants.DISTINCT);
        context.append(Constants.BLANK);
    }
}
